package com.tt.qiyuesuo.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tt.qiyuesuo.mapper.FileMapper;
import com.tt.qiyuesuo.pojo.FileInfo;
import lombok.Builder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.Date;
import java.util.List;

/**
 * @author tiantao
 * @date 2022/2/22 16:18
 */
@Service
@Slf4j
public class FileService {

    @Autowired
    FileMapper fileMapper;

    /**
     *
     * @param file
     */
    public void saveFileInfo(String originFileName,File file) {

        FileInfo fileInfo = FileInfo.builder()
                .size(file.length())
                .newFileName(file.getName())
                .originalFileName(originFileName)
                .creatTime(new Date()).path(file.getPath()).build();
        fileMapper.insert(fileInfo);

    }

    public String getPathByFileName(String fileName) {
        QueryWrapper<FileInfo> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("new_file_name",fileName);
        List<FileInfo> fileInfos = fileMapper.selectList(userQueryWrapper);
        if (fileInfos.size()==1) {
            return fileInfos.get(0).getPath();
        }
        return null;
    }

    public FileInfo getFileInfoByFileName(String fileName) {
        QueryWrapper<FileInfo> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("new_file_name",fileName);
        List<FileInfo> fileInfos = fileMapper.selectList(userQueryWrapper);
        if (fileInfos.size()==1) {
            return fileInfos.get(0);
        }
        return null;
    }
}
